<template>
  <div class="upload_container">
    <el-upload
      list-type="picture-card"
      accept="image/*"
      v-model:file-list="fileList"
      :action="uploadPath"
      :before-upload="uploadBefore"
      :on-change="uploadChange"
      :on-success="handleSuccess"
    >
      <template #trigger>
        <el-icon class="is-loading" v-if="state.uploading" size="30">
          <Loading />
        </el-icon>
        <el-icon v-else><Plus /></el-icon>
      </template>

      <template #file="{ file }">
        <div>
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <el-icon><zoom-in /></el-icon>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
              <el-icon><Delete /></el-icon>
            </span>
          </span>
        </div>
      </template>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <div class="view_img_box flex-center">
        <img :src="dialogImageUrl" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
const state = reactive({
  uploading: false
})

const emit = defineEmits(['upload-change'])

const uploadPath = `${import.meta.env.VITE_API_URL}/upload/file`

const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const uploadImgs = ref([])

function uploadBefore() {
  if (state.uploading) return
}

function uploadChange(res) {
  state.uploading = true
  if (res.status === 'success') {
    state.uploading = false
    // uploadImg.value = URL.createObjectURL(res.raw)
    // fileList.value = []
  }
  if (res.status === 'fail') {
    ElMessage.error({ message: 'Upload failed' })
    state.uploading = false
  }
}

function handleSuccess(res) {
  uploadImgs.value.push(res.data)
  emit('upload-change', uploadImgs.value)
}

function handleRemove(file) {
  let index = fileList.value.indexOf(file)
  fileList.value.splice(index, 1)
  uploadImgs.value.splice(index, 1)
  emit('upload-change', uploadImgs.value)
}

function handlePictureCardPreview(file) {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}
</script>
<style scoped lang="less"></style>
